package com.g360.sys.service;

import com.g360.sys.domain.Organization;
import com.g360.sys.domain.OrganizationExample;
import com.g360.sys.persistence.OrganizationMapper;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by vpc on 2016/4/1.
 */
@Service
@Transactional
public class OrganizationService {
    @Autowired
    private OrganizationMapper organizationMapper;

    public int createOrganization(Organization organization) {
        return organizationMapper.insert(organization);
    }

    public int updateOrganization(Organization organization) {
        return organizationMapper.insert(organization);
    }

    public void deleteOrganization(Long organizationId) {
        organizationMapper.deleteByPrimaryKey(organizationId);
    }

    public Organization findOne(Long organizationId) {
        return organizationMapper.selectByPrimaryKey(organizationId);
    }

    public List<Organization> findAll() {
        return organizationMapper.selectByExample(new OrganizationExample());
    }

    public List<Organization> findAllWithExclude(Organization excludeOrganization) {
        OrganizationExample organizationExample = new OrganizationExample();
        organizationExample.createCriteria()
                .andIdNotEqualTo(excludeOrganization.getId())
                .andParentIdsNotLike(excludeOrganization.makeSelfAsParentIds() + '%');

        return organizationMapper.selectByExample(organizationExample);

    }

    public void move(Organization source, Organization target) {
        source.setParentId(target.getId());
        source.setParentIds(target.getParentIds());
        organizationMapper.updateByPrimaryKey(source);

        Map<String,String> parameterMap = new HashMap<String,String>();
        parameterMap.put("makeSelfAsParentIds0",target.makeSelfAsParentIds());
        parameterMap.put("makeSelfAsParentIds1",source.makeSelfAsParentIds());

        organizationMapper.moveDescendants(parameterMap);
    }
}
